package cc.iotkit.manager.task;

import cc.iotkit.common.thing.ThingModelMessage;
import cc.iotkit.data.manager.IDeviceDailyReportData;
import cc.iotkit.data.manager.IDeviceInfoData;
import cc.iotkit.model.device.DeviceDailyReport;
import cc.iotkit.model.device.DeviceInfo;
import cc.iotkit.temporal.IThingModelMessageData;
import cn.hutool.json.JSONUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 同步当天所有设备的工作时长
 */
@Component
public class SyncWorkingTimesDaily {
    @Autowired
    private IDeviceInfoData deviceInfoData;
    @Autowired
    private IThingModelMessageData thingModelMessageData;
    @Autowired
    private IDeviceDailyReportData deviceDailyReportData;
    private static Logger logger = LoggerFactory.getLogger(SyncWorkingTimesDaily.class);
    //设置当前日期
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar c = Calendar.getInstance();

    Date startTime = null;
    Date endTime = null;
    @XxlJob("SyncWorkingTimes")
    public void run() throws Exception {
        logger.info("xxl-job:running SyncWorkingTimes...");
        String param = XxlJobHelper.getJobParam();
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        //前一天
        c.add(Calendar.DATE, -1);
        Date day = c.getTime();
        String yestoday= format.format(day);
        if(StringUtils.hasText(param)){
            yestoday=param;
        }
        startTime = sdf.parse(yestoday+" 00:00:00");
        endTime = sdf.parse(yestoday+" 23:59:59");

        this.exec(startTime,endTime);
    }

    private void exec(Date startTime,Date endTime){
        try {
            List<DeviceInfo> list= deviceInfoData.findAll();
            List<DeviceDailyReport> reports=new ArrayList<>();
            for(DeviceInfo info : list){
                List<ThingModelMessage> messageList= thingModelMessageData.findWorkingStatusLog(info.getDeviceId(),startTime.getTime(),endTime.getTime());
                if(messageList.size()>0) {
                    Long onlineSecends = this.getOnlineSecends(messageList);
                    DeviceDailyReport report = new DeviceDailyReport();
                    report.setWorkingTimes(onlineSecends);
                    report.setReportDate(endTime);
                    report.setDeviceId(info.getDeviceId());
                    reports.add(report);
                }else{
                    //判断是否连续工作几天
                    //如果当天无工作状态，查询最近一次的工作状态，如果为工作中，补充开始时间
                    messageList= thingModelMessageData.findLastWorkingStatus(startTime.getTime(),info.getDeviceId());
                    if(messageList.size()>0){
                        String status= JSONUtil.parse(messageList.get(0).getData()).getByPath("status").toString();
                        if(status.equals("1")){
                            messageList.get(0).setTime(startTime.getTime());
                            Long onlineSecends = this.getOnlineSecends(messageList);
                            DeviceDailyReport report = new DeviceDailyReport();
                            report.setWorkingTimes(onlineSecends);
                            report.setReportDate(endTime);
                            report.setDeviceId(info.getDeviceId());
                            reports.add(report);
                        }
                    }

                }
            }

            deviceDailyReportData.batchSave(reports);

            logger.info("xxl-job:running SyncWorkingTimes finished");
        }
        catch (Exception e){
            logger.info("xxl-job-error:"+e.getMessage());
            XxlJobHelper.log(e);
            XxlJobHelper.handleFail();
        }
    }
    private Long getOnlineSecends(List<ThingModelMessage> messageList){
        //判断第一条，是否需要填充登入
        ThingModelMessage message= messageList.get(0);
        String status= JSONUtil.parse(message.getData()).getByPath("status").toString();

        //补充开始时间
        if(status.equals("0")){
            ThingModelMessage msg=new ThingModelMessage();
            msg.setDeviceId(message.getDeviceId());
            msg.setTime(startTime.getTime());
            msg.setData("{\"status\":\"1\"}");
            messageList.add(0,msg);
        }
        //判断最后一条，是否需要填充登出
        message= messageList.get(messageList.size()-1);
        String status1= JSONUtil.parse(message.getData()).getByPath("status").toString();
        if(status1.equals("1")){
            ThingModelMessage msg=new ThingModelMessage();
            msg.setDeviceId(message.getDeviceId());
            msg.setTime(endTime.getTime());
            msg.setData("{\"status\":\"0\"}");
            messageList.add(msg);
        }
        Long onlineSeconds=0L;
        Long onlineTime=0L;
        String lastStatus="";
        //计算在线时间
        for(ThingModelMessage row: messageList){
            String status2= JSONUtil.parse(row.getData()).getByPath("status").toString();
            if(lastStatus.equals(status2)){
                continue;
            }else{
                lastStatus=status2;
            }
            if(status2.equals("1")){
                onlineTime=row.getTime();
            }
            else{
                onlineSeconds+=row.getTime()-onlineTime;
            }
        }

        return onlineSeconds/1000;
    }

}
